# coding=utf-8

from service.basesv import BaseSV
from tools.cachedata import CacheData
from tools.cachedataclient import CacheDataClient
from tools.http import http


class PaymentSV(BaseSV):

    def alert_scan_qrcode(self):
        http(self.alert_scan_qrcode_url, {}, "GET")

    def push(self, trade_no, consume, bill, date_time, summary="无", state="In"):
        """
        推送账单
          1.判断交易是否重复
          2.拼接路径
          3.push到服务器
        :param trade_no: 交易流水号
        :param consume:对方账户信息
        :param money:交易金额
        :param state:状态
        :param date_time:具体时间
        :param summary:备注
        :return:
        """

        # 1.判断交易是否重复
        cache_data_client = CacheDataClient()
        cache_data = CacheData().toObj(cache_data_client.read())

        token = cache_data.get_token
        trade_num_last = cache_data.get_trade_no
        if trade_num_last.__eq__(str(trade_no)):
            return False
        else:
            # 记录已经有的交易记录
            cache_data.set_trade_no = trade_no
            cache_data_client.write(cache_data.toJson())

        # 2.拼接路径
        # bill 账款; state 进账In，出账 Out;  time 时间; consume 对方; tradeNo 交易流水号;
        if bill < 0:
            state = "Out"
        data = {
            'bill': str(bill),
            'tradeNo': trade_no,
            'consume': consume,
            'state': state,
            'summary': summary,
            'time': date_time,
            'token': token
        }
        return http(self.bill_url, data, "POST")
        # postdata = parse.urlencode(data).encode('utf-8')
        # # 3.push到服务器
        # req = request.Request(self.bill_url, data=postdata, method='POST')
        # req.add_header(self.authorization, cache_data.get_token)
        # response = request.urlopen(req)
        # result = response.read()
        # beanret = BeanRet().toObj(result)
        # if beanret.getSuccess:
        #     refresh_token = response.headers.get(self.authorization)
        #     if refresh_token:
        #         cache_data.token = refresh_token
        #         cache_data_client.write(cache_data.toJson())
        #
        #     return True
        # else:
        #     return False
